<?php
namespace Cmf\Controllers;

use Cmf\Models\Menu;
use Cmf\Models\Tree;
use Cmf\Models\Role;
use Cmf\Models\Permission;

/**
 * 权限管理控制器
 */
class PermissionController extends BaseController
{
	/*权限列表*/
	public function newAction()
	{
		$role = Role::find();
		$menu = Menu::find();
		$node = tree::listToTree($menu->toArray());

		$identity = $this->session->get('auth_identity');
		$permission = Permission::find('role_id='.$identity['role_id']);

		$url = array();
		foreach($permission as $value) {
			$url[] = $value->controller.'/'.$value->action;
		}

		$this->view->url = $url;
		$this->view->roles = $role;
		$this->view->nodes = $node;
		$this->view->current_id = $identity['role_id'];
	}

	public function createAction()
	{
		if($this->request->isPost()) {

			$nodes = array_unique($this->request->getPost('node'));
			$role_id = $this->request->getPost('role_id');

			if(!$role_id) {
				$this->flash->error('请选择权限角色');

				return $this->dispatcher->forward(['controller' => 'permission','action' => 'new']);
			}

			$role = Role::findFirst("id = '{$role_id}'");
			if(($role->getPermissions()->delete()) === false) {
				$this->flash->error('删除权限失败');

				return $this->dispatcher->forward(['controller' => 'permission','action' => 'new']);
			}

			foreach($nodes as $node) {
				$node = explode('/',$node);

				$permission = new Permission();
				$permission->controller = $node[0];
				$permission->action = $node[1];
				$permission->role_id = $role_id;

				if(!$permission->create()) {
					foreach($permission->getMessages() as $key => $message) {
						$this->flash->error($message);
					}

					return $this->dispatcher->forward(['controller' => 'permission','action' => 'new']);
				}
			}

			$this->acl->rebuild();

			$this->flash->success('权限更新成功');

			return $this->response->redirect('permission/new');
		}
	}

}
